#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通用进度条控件
支持多种风格和白天/黑夜模式的进度条组件

Author: MooeTool Development Team
Version: 1.0
Date: 2024
License: MIT

This module provides a customizable progress bar widget with multiple styles
and day/night theme support, with hardcoded QSS styles for better control.
"""

import sys
from enum import Enum
from typing import Optional, Dict, Any, Union
from PySide2.QtWidgets import (
    QProgressBar, QWidget, QVBoxLayout, QHBoxLayout, 
    QLabel, QPushButton, QApplication
)
from PySide2.QtCore import Qt, Signal, QTimer, QPropertyAnimation, QEasingCurve
from PySide2.QtGui import QFont, QPalette, QColor

class ProgressStyle(Enum):
    """进度条样式枚举"""
    TRANSFER = "transfer"  # 文件传输样式
    GENERAL = "general"   # 通用样式
    SUCCESS = "success"   # 成功样式
    WARNING = "warning"   # 警告样式
    ERROR = "error"       # 错误样式
    MODERN = "modern"     # 现代样式
    MINIMAL = "minimal"   # 简约样式

class ThemeMode(Enum):
    """主题模式枚举"""
    LIGHT = "light"  # 白天模式
    DARK = "dark"    # 黑夜模式

class CustomProgressBar(QProgressBar):
    """自定义进度条控件"""
    
    # 信号定义
    progress_changed = Signal(int)  # 进度值变化
    style_changed = Signal(str, str)  # 样式变化 (style, theme)
    animation_finished = Signal()  # 动画完成
    
    def __init__(self, 
                 style: ProgressStyle = ProgressStyle.GENERAL,
                 theme: ThemeMode = ThemeMode.LIGHT,
                 parent: Optional[QWidget] = None):
        super().__init__(parent)
        
        self._style = style
        self._theme = theme
        self._animated = False
        self._animation_timer = QTimer()
        self._animation_timer.timeout.connect(self._update_animation)
        
        # 初始化进度条
        self.setMinimum(0)
        self.setMaximum(100)
        self.setValue(0)
        
        # 应用样式
        self.apply_style()
        
        # 连接信号
        self.valueChanged.connect(self._on_value_changed)
    
    def _on_value_changed(self, value: int):
        """进度值变化处理"""
        self.progress_changed.emit(value)
    
    def apply_style(self):
        """应用当前样式和主题"""
        qss = self._get_style_qss()
        self.setStyleSheet(qss)
        self.style_changed.emit(self._style.value, self._theme.value)
    
    def set_style(self, style: ProgressStyle, theme: Optional[ThemeMode] = None):
        """设置样式"""
        self._style = style
        if theme is not None:
            self._theme = theme
        self.apply_style()
    
    def set_theme(self, theme: ThemeMode):
        """设置主题"""
        self._theme = theme
        self.apply_style()
    
    def toggle_theme(self):
        """切换主题"""
        new_theme = ThemeMode.DARK if self._theme == ThemeMode.LIGHT else ThemeMode.LIGHT
        self.set_theme(new_theme)
    
    def _get_style_qss(self) -> str:
        """获取当前样式的QSS代码"""
        base_qss = self._get_base_qss()
        style_qss = self._get_style_specific_qss()
        theme_qss = self._get_theme_specific_qss()
        
        return f"{base_qss}\n{style_qss}\n{theme_qss}"
    
    def _get_base_qss(self) -> str:
        """获取基础QSS样式"""
        return """
        QProgressBar {
            border-radius: 8px;
            text-align: center;
            font-weight: bold;
            min-height: 28px;
            font-size: 13px;
            padding: 2px;
        }
        
        QProgressBar::chunk {
            border-radius: 6px;
            margin: 2px;
        }
        """
    
    def _get_style_specific_qss(self) -> str:
        """获取样式特定的QSS"""
        style_map = {
            ProgressStyle.TRANSFER: self._get_transfer_style(),
            ProgressStyle.GENERAL: self._get_general_style(),
            ProgressStyle.SUCCESS: self._get_success_style(),
            ProgressStyle.WARNING: self._get_warning_style(),
            ProgressStyle.ERROR: self._get_error_style(),
            ProgressStyle.MODERN: self._get_modern_style(),
            ProgressStyle.MINIMAL: self._get_minimal_style(),
        }
        return style_map.get(self._style, self._get_general_style())
    
    def _get_theme_specific_qss(self) -> str:
        """获取主题特定的QSS"""
        if self._theme == ThemeMode.LIGHT:
            return self._get_light_theme_qss()
        else:
            return self._get_dark_theme_qss()
    
    def _get_transfer_style(self) -> str:
        """文件传输样式"""
        if self._theme == ThemeMode.LIGHT:
            return """
            QProgressBar {
                border: 2px solid #bdc3c7;
                background-color: #ecf0f1;
                color: #2c3e50;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #3498db, 
                    stop: 0.3 #5dade2,
                    stop: 0.7 #3498db,
                    stop: 1 #2980b9
                );
            }
            """
        else:
            return """
            QProgressBar {
                border: 2px solid #34495e;
                background-color: #2c3e50;
                color: #ecf0f1;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #5dade2, 
                    stop: 0.3 #3498db,
                    stop: 0.7 #5dade2,
                    stop: 1 #85c1e9
                );
            }
            """
    
    def _get_general_style(self) -> str:
        """通用样式"""
        if self._theme == ThemeMode.LIGHT:
            return """
            QProgressBar {
                border: 2px solid #95a5a6;
                background-color: #f8f9fa;
                color: #2c3e50;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #6c757d, 
                    stop: 0.5 #495057,
                    stop: 1 #343a40
                );
            }
            """
        else:
            return """
            QProgressBar {
                border: 2px solid #6c757d;
                background-color: #343a40;
                color: #f8f9fa;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #adb5bd, 
                    stop: 0.5 #868e96,
                    stop: 1 #6c757d
                );
            }
            """
    
    def _get_success_style(self) -> str:
        """成功样式"""
        if self._theme == ThemeMode.LIGHT:
            return """
            QProgressBar {
                border: 2px solid #27ae60;
                background-color: #d5f4e6;
                color: #155724;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #27ae60, 
                    stop: 0.5 #2ecc71,
                    stop: 1 #58d68d
                );
            }
            """
        else:
            return """
            QProgressBar {
                border: 2px solid #58d68d;
                background-color: #1e3a2e;
                color: #d5f4e6;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #58d68d, 
                    stop: 0.5 #2ecc71,
                    stop: 1 #85e0a3
                );
            }
            """
    
    def _get_warning_style(self) -> str:
        """警告样式"""
        if self._theme == ThemeMode.LIGHT:
            return """
            QProgressBar {
                border: 2px solid #f39c12;
                background-color: #fef9e7;
                color: #856404;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #f39c12, 
                    stop: 0.5 #f1c40f,
                    stop: 1 #f7dc6f
                );
            }
            """
        else:
            return """
            QProgressBar {
                border: 2px solid #f7dc6f;
                background-color: #3d3a1a;
                color: #fef9e7;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #f7dc6f, 
                    stop: 0.5 #f1c40f,
                    stop: 1 #fcf3cf
                );
            }
            """
    
    def _get_error_style(self) -> str:
        """错误样式"""
        if self._theme == ThemeMode.LIGHT:
            return """
            QProgressBar {
                border: 2px solid #e74c3c;
                background-color: #fadbd8;
                color: #721c24;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #e74c3c, 
                    stop: 0.5 #ec7063,
                    stop: 1 #f1948a
                );
            }
            """
        else:
            return """
            QProgressBar {
                border: 2px solid #f1948a;
                background-color: #3a1f1f;
                color: #fadbd8;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #f1948a, 
                    stop: 0.5 #ec7063,
                    stop: 1 #f5b7b1
                );
            }
            """
    
    def _get_modern_style(self) -> str:
        """现代样式"""
        if self._theme == ThemeMode.LIGHT:
            return """
            QProgressBar {
                border: 1px solid #e9ecef;
                background-color: #ffffff;
                color: #495057;
                border-radius: 12px;
                min-height: 24px;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #667eea, 
                    stop: 0.5 #764ba2,
                    stop: 1 #f093fb
                );
                border-radius: 10px;
            }
            """
        else:
            return """
            QProgressBar {
                border: 1px solid #495057;
                background-color: #212529;
                color: #adb5bd;
                border-radius: 12px;
                min-height: 24px;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #a8edea, 
                    stop: 0.5 #fed6e3,
                    stop: 1 #d299c2
                );
                border-radius: 10px;
            }
            """
    
    def _get_minimal_style(self) -> str:
        """简约样式"""
        if self._theme == ThemeMode.LIGHT:
            return """
            QProgressBar {
                border: none;
                background-color: #f8f9fa;
                color: #6c757d;
                border-radius: 2px;
                min-height: 8px;
                font-size: 11px;
            }
            QProgressBar::chunk {
                background-color: #007bff;
                border-radius: 1px;
                margin: 1px;
            }
            """
        else:
            return """
            QProgressBar {
                border: none;
                background-color: #343a40;
                color: #adb5bd;
                border-radius: 2px;
                min-height: 8px;
                font-size: 11px;
            }
            QProgressBar::chunk {
                background-color: #17a2b8;
                border-radius: 1px;
                margin: 1px;
            }
            """
    
    def _get_light_theme_qss(self) -> str:
        """浅色主题通用样式"""
        return """
        QProgressBar {
            selection-background-color: transparent;
        }
        """
    
    def _get_dark_theme_qss(self) -> str:
        """深色主题通用样式"""
        return """
        QProgressBar {
            selection-background-color: transparent;
        }
        """
    
    def set_animated_progress(self, target_value: int, duration: int = 1000):
        """设置动画进度"""
        if hasattr(self, '_animation'):
            self._animation.stop()
        
        from PySide2.QtCore import QPropertyAnimation
        self._animation = QPropertyAnimation(self, b"value")
        self._animation.setDuration(duration)
        self._animation.setStartValue(self.value())
        self._animation.setEndValue(target_value)
        self._animation.setEasingCurve(QEasingCurve.OutCubic)
        self._animation.finished.connect(self.animation_finished.emit)
        self._animation.start()
    
    def start_pulse_animation(self):
        """开始脉冲动画"""
        self._animated = True
        self._animation_timer.start(50)  # 50ms间隔
    
    def stop_pulse_animation(self):
        """停止脉冲动画"""
        self._animated = False
        self._animation_timer.stop()
    
    def _update_animation(self):
        """更新动画效果"""
        if not self._animated:
            return
        
        # 简单的脉冲效果 - 可以根据需要扩展
        current_style = self.styleSheet()
        # 这里可以添加更复杂的动画逻辑

class ProgressBarFactory:
    """进度条工厂类"""
    
    @staticmethod
    def create_progress_bar(style: Union[str, ProgressStyle] = ProgressStyle.GENERAL,
                          theme: Union[str, ThemeMode] = ThemeMode.LIGHT,
                          parent: Optional[QWidget] = None) -> CustomProgressBar:
        """创建进度条实例"""
        # 转换字符串参数为枚举
        if isinstance(style, str):
            try:
                style = ProgressStyle(style)
            except ValueError:
                style = ProgressStyle.GENERAL
        
        if isinstance(theme, str):
            try:
                theme = ThemeMode(theme)
            except ValueError:
                theme = ThemeMode.LIGHT
        
        return CustomProgressBar(style, theme, parent)
    
    @staticmethod
    def get_available_styles() -> list:
        """获取可用样式列表"""
        return [style.value for style in ProgressStyle]
    
    @staticmethod
    def get_available_themes() -> list:
        """获取可用主题列表"""
        return [theme.value for theme in ThemeMode]

# 便捷函数
def create_transfer_progress(theme: ThemeMode = ThemeMode.LIGHT, parent: Optional[QWidget] = None) -> CustomProgressBar:
    """创建文件传输进度条"""
    return ProgressBarFactory.create_progress_bar(ProgressStyle.TRANSFER, theme, parent)

def create_general_progress(theme: ThemeMode = ThemeMode.LIGHT, parent: Optional[QWidget] = None) -> CustomProgressBar:
    """创建通用进度条"""
    return ProgressBarFactory.create_progress_bar(ProgressStyle.GENERAL, theme, parent)

def create_success_progress(theme: ThemeMode = ThemeMode.LIGHT, parent: Optional[QWidget] = None) -> CustomProgressBar:
    """创建成功进度条"""
    return ProgressBarFactory.create_progress_bar(ProgressStyle.SUCCESS, theme, parent)

def create_warning_progress(theme: ThemeMode = ThemeMode.LIGHT, parent: Optional[QWidget] = None) -> CustomProgressBar:
    """创建警告进度条"""
    return ProgressBarFactory.create_progress_bar(ProgressStyle.WARNING, theme, parent)

def create_error_progress(theme: ThemeMode = ThemeMode.LIGHT, parent: Optional[QWidget] = None) -> CustomProgressBar:
    """创建错误进度条"""
    return ProgressBarFactory.create_progress_bar(ProgressStyle.ERROR, theme, parent)

def create_modern_progress(theme: ThemeMode = ThemeMode.LIGHT, parent: Optional[QWidget] = None) -> CustomProgressBar:
    """创建现代进度条"""
    return ProgressBarFactory.create_progress_bar(ProgressStyle.MODERN, theme, parent)

def create_minimal_progress(theme: ThemeMode = ThemeMode.LIGHT, parent: Optional[QWidget] = None) -> CustomProgressBar:
    """创建简约进度条"""
    return ProgressBarFactory.create_progress_bar(ProgressStyle.MINIMAL, theme, parent)

# 测试代码
if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 创建测试窗口
    widget = QWidget()
    widget.setWindowTitle("Custom Progress Bar Test")
    widget.setGeometry(200, 200, 600, 400)
    
    layout = QVBoxLayout()
    
    # 创建不同样式的进度条
    styles = [
        (ProgressStyle.TRANSFER, "Transfer Style"),
        (ProgressStyle.GENERAL, "General Style"),
        (ProgressStyle.SUCCESS, "Success Style"),
        (ProgressStyle.WARNING, "Warning Style"),
        (ProgressStyle.ERROR, "Error Style"),
        (ProgressStyle.MODERN, "Modern Style"),
        (ProgressStyle.MINIMAL, "Minimal Style"),
    ]
    
    progress_bars = []
    
    for style, name in styles:
        # 浅色主题
        label_light = QLabel(f"{name} - Light Theme")
        layout.addWidget(label_light)
        
        pb_light = CustomProgressBar(style, ThemeMode.LIGHT)
        pb_light.setValue(60)
        pb_light.setFormat(f"{name} - 60%")
        layout.addWidget(pb_light)
        progress_bars.append(pb_light)
        
        # 深色主题
        label_dark = QLabel(f"{name} - Dark Theme")
        layout.addWidget(label_dark)
        
        pb_dark = CustomProgressBar(style, ThemeMode.DARK)
        pb_dark.setValue(60)
        pb_dark.setFormat(f"{name} - 60%")
        layout.addWidget(pb_dark)
        progress_bars.append(pb_dark)
    
    widget.setLayout(layout)
    widget.show()
    
    sys.exit(app.exec_())